using UnityEngine;

public class FPS : MonoBehaviour 
{
	public float fps; // Current FPS
	public float smoothFps; // Smoothed FPS
	public float minFps; // min FPS
	public float maxFps; // max FPS
	
	private const int nLastFpsCount = 100;
	private int nLastFpsNum = 0;
	private float[] fLastFpsArray;
	private float fCummulFps;
	private System.Diagnostics.Stopwatch timer;
	private long lastTick;
	
	void Start()
	{
		fLastFpsArray = new float[nLastFpsCount];
		fCummulFps = 0f;
		minFps = float.MaxValue;
		maxFps = float.MinValue;
		timer = new System.Diagnostics.Stopwatch();
		timer.Start();		
	}

	void Update()
	{
		long currentTick = timer.ElapsedTicks;
			
		fps = (float)( (double)System.Diagnostics.Stopwatch.Frequency / (double)(currentTick - lastTick) );
		lastTick = currentTick;
		
		fCummulFps += fps - fLastFpsArray[nLastFpsNum];
		
		smoothFps = fCummulFps / nLastFpsCount;
		
		fLastFpsArray[nLastFpsNum] = fps;
		nLastFpsNum++;
		if( nLastFpsNum == nLastFpsCount )
			nLastFpsNum = 0;
		
		if( minFps > fps )
			minFps = fps;
		if( maxFps < fps )
			maxFps = fps;

//		Debug.Log( "fps " + fps + " smoothFps " + smoothFps + " minFps " + minFps + " maxFps " + maxFps );
	}
	
	public void ClearStats()
	{
		minFps = float.MaxValue;
		maxFps = float.MinValue;
	}

	void OnGUI()
	{
		GUI.Label(new Rect(5,5,100,20),fps.ToString("f2"));
	}
}

